<!--//资源首页-->
<script setup>
import { ArrowDown } from '@element-plus/icons-vue';
import requester from "~/utils/request";
import { userStore } from "~/composables/useUserStore";
const store = userStore();


//增加SEO
useHead({
  title: '资源首页 - 迅颖',
  titleTemplate:"资源首页 - 迅颖",
  meta: [
    { hid: 'keywords', name: 'keywords', content: '项目' }
  ]
})
const state = reactive({
  loading: false,
  categorys: "",
  productName: "",
  suffix: "",
  productType: 2,
  tabIndex: 0,
  tabIndex2: 0,
  tabList: [],
  tabList2: [],
  suffixList: [],
  filterList: [
    {
      label: "全部",
      value: ""
    },
    {
      label: "免费",
      value: "2"
    },
    {
      label: "付费",
      value: "1"
    }
  ],
  priceForm: "",
  goodsList: [],
  pageValidate: {
    pageNo: 1,
    pageSize: 8
  },
  total: 8,

})

function querySearchAsync(queryString, cb) {
  let form = {
    "pageValidate": {
      "pageNo": 1,
      "pageSize": 10
    },
    "productName": queryString,
    "productType": 2,
  }
  requester.post('api/product/searchLikeMatch', form).then(res => {
    console.log(res);
    let list = []
    res.data.lists.forEach(element => {
      list.push({
        value: element.text
      })
    });

    cb(list)
  })
}

/**
 * 获取类别
 */
function getCategoryList() {
  requester.post('api/category/categoryList', { channel: 2 }).then(res => {
    state.tabList = res.data
    state.tabList.unshift({ categoryName: '全部', categoryId: '' })
  })
}

/**
 * 获取商品
 */
function getGoodsList() {
  state.loading = true
  const param = {
    productType: state.productType,
    pageValidate: state.pageValidate,
    categorys: state.categorys,
    productName: state.productName,
    priceForm: state.priceForm,
    suffix: state.suffix,
    userCode: store.token.userCode
  }
  if (!param.productName) delete param.productName
  if (!param.priceForm) delete param.priceForm
  if (!param.categorys) delete param.categorys
  if (!param.suffix) delete param.suffix
  if (!param.userCode) delete param.userCode

  requester.post('/api/product/searchProduct', param).then((res) => {
    if (res.code == 200) {
      state.total = res.data.count
      state.goodsList.push(...res.data.lists)
      console.log(state.goodsList);

      state.loading = false
    }
  })
}
function search() {
  state.pageValidate.pageNo = 1
  state.goodsList = []
  getGoodsList()
}

onMounted(() => {
  window.addEventListener("scroll", debounce(handleScroll), false);
})


//滚动高度赋值
function handleScroll() {
  let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  let clientHeight = document.documentElement.clientHeight;
  let scrollHeight = document.documentElement.scrollHeight;
  if (scrollTop + clientHeight + 20 >= scrollHeight) {
    if (state.goodsList.length == state.total) return
    state.pageValidate.pageNo++
    getGoodsList()
  }
}

//防抖 滚动结束执行
function debounce(fn, interval = 500) {
  let timeout = null;

  return function () {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      fn.apply(this, arguments);
    }, interval);
  };
}

//移除监听 组件实例被卸载后调用
onUnmounted(() => {
  // console.log('onUnmounted');
  window.removeEventListener('scroll', debounce(handleScroll), false);
});


function tabClick(item, key, value) {
  state[key] = item[value]
  search()
}


function clickCategory(item) {
  requester.post('/api/category/clickCategory', {
    firstSysId: item.categoryId
  }).then((res) => {
    if (res.code == 200) {
      state.tabList2 = res.data
      if (state.tabList2.length > 0) {
        state.tabList2.unshift({ categoryName: '全部', categoryId: '' })
      }
    }
  })
}

function getSuffix() {
  requester.post('/api/product/getSuffix', {
    productType: state.productType,
    pageValidate: state.pageValidate
  }).then(res => {
    let lists = [
      {
        label: "全部",
        value: ''
      }
    ]
    for (let index = 0; index < res.data.lists.length; index++) {
      const element = res.data.lists[index];
      lists.push({
        label: element.suffix,
        value: element.suffix
      })
    }
    state.suffixList = lists

  })
}

function getHotProduct() {
  requester.post('/api/product/hotProduct', {
    productType: 2,
    pageValidate: {
      pageNo: 1,
      pageSize: 10
    },
  }).then(res => {
    state.hotList = res.data.lists
  })
}
getCategoryList()
getSuffix()
getHotProduct()
search()

</script>

<template>
  <myheader />
  <main class="main">
    <section class="bgCon">
      <div class="bgConChild bgConChild1"></div>
      <div class="bgConChild bgConChild2"></div>
      <div class="bgConChild bgConChild3"></div>
    </section>
    <div class="conWarp">
      <nav class="bannerCon">
        <img src="~/assets/resources/index/bannerBg.png" alt="" class="bannerBg">
        <img src="~/assets/resources/index/bannerTitle.png" alt="" class="bannerTitle">
        <div class="searchCon">
          <el-autocomplete v-model="state.productName" :fetch-suggestions="querySearchAsync" placeholder="请输入"
            @select="search" @keyup.enter="search()"></el-autocomplete>
          <div class="searchBtn" @click="search()">
            <img src="~/assets/resources/index/searchIcon1.png" alt="" class="searchIcon1">
            <img src="~/assets/resources/index/searchIcon2.png" alt="" class="searchIcon2">
          </div>
        </div>
      </nav>

      <nav class="filterCon">
        <section>
          <h1 class="title">方向：</h1>
          <div class="filterItems">
            <section v-for="(item, index) in state.tabList"
              :class="[state.tabIndex == index ? 'active' : '', 'filterItem']"
              @click="tabClick(item, 'categorys', 'categoryId'); clickCategory(item); state.tabIndex = index; state.tabIndex2 = 0">
              {{
                item.categoryName }}</section>
          </div>
        </section>
        <section v-show="state.tabList2.length > 0">
          <div class="filterItems">
            <section v-for="(item, index) in state.tabList2"
              :class="[state.tabIndex2 == index ? 'active' : '', 'filterItem']"
              @click="tabClick(item, 'categorys', 'categoryId'); state.tabIndex2 = index;">{{
                item.categoryName }}</section>
          </div>
        </section>
      </nav>

      <section class="selectCon">
        <div class="selectItem">
          <el-dropdown trigger="click">
            <el-button>
              形式
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :class="state.priceForm == item.value ? 'active' : ''"
                  v-for="item in state.filterList" @click="tabClick(item, 'priceForm', 'value')">{{ item.label
                  }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div class="selectItem">
          <el-dropdown trigger="click">
            <el-button>
              格式
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <template v-for="item in state.suffixList">
                  <el-dropdown-item v-if="item.label" @click="tabClick(item, 'suffix', 'value')">{{
                    item.label }}</el-dropdown-item>
                </template>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </section>

      <section class="conWarp-box">
        <article class="conWarp-left">
          <section class="listCon">
            <resourceList v-if="state.goodsList && state.goodsList.length>0" :articleList="state.goodsList" />
            <el-empty v-else description="暂无数据" />
          </section>
        </article>

        <aside class="conWarp-right">
          <rightLogin />
          <creationCenter />
          <hotArticles :hotList="state.hotList" />
        </aside>
      </section>

    </div>
  </main>
  <myFooter />
</template>

<style scoped lang="scss">
@import "./scss/index.scss";
</style>
